package spotGUI.personalProfileGUI;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.Box;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.ListCellRenderer;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;

import managers.DBManager;
import managers.socialNetworkManagers.SocialNetworkManager;
import net.tomahawk.ExtensionsFilter;
import net.tomahawk.XFileDialog;
import personalProfile.PersonalProfile;
import spotGUI.ElementViewer.ElementPanel;
import utils.ImageUtils;
import utils.MaxLenghtTextDocument;
import utils.Mood;
import utils.SocialUserData;
import utils.StackTracePrinter;
import java.awt.Cursor;
import javax.swing.JProgressBar;
import java.util.ResourceBundle;

public class PersonalProfileFrame extends JFrame {

	private static final int MAX_PERSONAL_PHOTO_HEIGHT = 128;




	private SocialNetworkManager manager = SocialNetworkManager.getSharedInstance();

	private JLabel lblUserName;
	private JTabbedPane tabbedPane;

	private JScrollPane scrollPanePersonalData;
	private JTextField lblNickName;
	private JButton btnModifyProfile;
	private JButton btnUpdateProfile;
	private JTextPane personalMessage;
	private JLabel lblTitle;
	private JLabel imageMood;
	private Box horizontalBox;
	private JLabel lblMood;

	private SocialUserData user;
	private JComboBox comboBoxMood;
	private JLabel lblUserphoto;
	private JButton btnChangeProfileImage;

	private PersonalProfile profile;

	private ImageIcon newUserPhoto = null;
	private XFileDialog fileChooser = null;

	private ElementPanel personalElementsPanel;

	private ActionListener changeImageListener = new ActionListener() {
		public void actionPerformed(ActionEvent arg0) {
			if (fileChooser == null) {
				fileChooser = new XFileDialog("Scegli immagine");
				Vector<String> extensions = new Vector<String>();
				extensions.addElement("png");
				extensions.addElement("jpg");
				extensions.addElement("bmp");
				fileChooser.addFilters(new ExtensionsFilter("File immagine", extensions));
			}
			String filename = fileChooser.getFile();
			String directory = fileChooser.getDirectory();
			if (filename != null) {
				newUserPhoto = new ImageIcon(directory+filename);
				if (newUserPhoto.getIconHeight() > MAX_PERSONAL_PHOTO_HEIGHT)
					newUserPhoto = ImageUtils.resize(newUserPhoto, -1, MAX_PERSONAL_PHOTO_HEIGHT);
			}
			lblUserphoto.setIcon(newUserPhoto);
		}
	};
	private Box horizontalBox_1;
	private JSplitPane splitPane;
	private Box verticalBox;
	private JProgressBar progressBar;





	public PersonalProfileFrame(final PersonalProfile profile) {

		this.profile = profile;

		GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
		setMaximizedBounds(env.getMaximumWindowBounds());

		setTitle(ResourceBundle.getBundle("spotGUI.personalProfileGUI.messages").getString("PersonalProfileFrame.this.title")); //$NON-NLS-1$ //$NON-NLS-2$
		setIconImage(Toolkit.getDefaultToolkit().getImage(PersonalProfileFrame.class.getResource("/images/Icons/64x64/users_comments.png")));
		setMinimumSize(new Dimension(800, 600));

		setLocationRelativeTo(null);

		JPanel contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(10, 10, 10 ,10));
		setContentPane(contentPane);


		user = manager.getUser(profile.getUserId());

		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		GridBagLayout gbl_contentPane = new GridBagLayout();
		gbl_contentPane.columnWidths = new int[]{421, 65, 61};
		gbl_contentPane.rowHeights = new int[]{4, 47, 28, 24, 31, 33, 314, 0};
		gbl_contentPane.columnWeights = new double[]{0.0, 1.0, 0.0};
		gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
		getContentPane().setLayout(gbl_contentPane);



		horizontalBox_1 = Box.createHorizontalBox();
		GridBagConstraints gbc_horizontalBox_1 = new GridBagConstraints();
		gbc_horizontalBox_1.fill = GridBagConstraints.BOTH;
		gbc_horizontalBox_1.gridheight = 4;
		gbc_horizontalBox_1.insets = new Insets(0, 0, 5, 5);
		gbc_horizontalBox_1.gridx = 0;
		gbc_horizontalBox_1.gridy = 0;
		contentPane.add(horizontalBox_1, gbc_horizontalBox_1);

		lblUserphoto = new JLabel("");
		lblUserphoto.setIcon(new ImageIcon(PersonalProfileFrame.class.getResource("/images/Icons/128x128/user.png")));
		lblUserphoto.setToolTipText(ResourceBundle.getBundle("spotGUI.personalProfileGUI.messages").getString("PersonalProfileFrame.lblUserphoto.toolTipText")); //$NON-NLS-1$ //$NON-NLS-2$
		horizontalBox_1.add(lblUserphoto);
		lblUserphoto.setBorder(new EtchedBorder(EtchedBorder.RAISED, null, null));
		new Thread () {
			public void run() {
				try {
					lblUserphoto.setIcon(profile.retrievePersonalPhoto(DBManager.getConnection()));
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					StackTracePrinter.print(e1);
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					StackTracePrinter.print(e1);
				}
			};
		}.start();


		verticalBox = Box.createVerticalBox();
		horizontalBox_1.add(verticalBox);

		lblTitle = new JLabel("");
		lblTitle.setAlignmentX(Component.RIGHT_ALIGNMENT);
		verticalBox.add(lblTitle);
		lblTitle.setAlignmentY(Component.TOP_ALIGNMENT);
		lblTitle.setIcon(new ImageIcon(PersonalProfileFrame.class.getResource("/images/GUIBackgrounds/profile.png")));

		lblUserName = new JLabel("userName");
		lblUserName.setAlignmentX(Component.RIGHT_ALIGNMENT);
		lblUserName.setVerticalAlignment(SwingConstants.TOP);
		verticalBox.add(lblUserName);
		lblUserName.setOpaque(false);
		lblUserName.setHorizontalAlignment(SwingConstants.RIGHT);
		lblUserName.setAlignmentY(Component.TOP_ALIGNMENT);
		lblUserName.setFont(new Font("Agency FB", Font.BOLD, 42));

		lblNickName = new JTextField();
		lblNickName.setToolTipText(ResourceBundle.getBundle("spotGUI.personalProfileGUI.messages").getString("PersonalProfileFrame.lblNickName.toolTipText")); //$NON-NLS-1$ //$NON-NLS-2$
		lblNickName.setDocument(new MaxLenghtTextDocument(25));
		verticalBox.add(lblNickName);
		lblNickName.setEditable(false);
		lblNickName.setBorder(null);
		lblNickName.setOpaque(false);
		lblNickName.setHorizontalAlignment(SwingConstants.RIGHT);
		lblNickName.setFont(new Font("Dialog", Font.PLAIN, 17));
		lblNickName.setAlignmentY(Component.TOP_ALIGNMENT);
		lblNickName.setText(ResourceBundle.getBundle("spotGUI.personalProfileGUI.messages").getString("PersonalProfileFrame.lblNickName.text")); //$NON-NLS-1$ //$NON-NLS-2$

		lblMood = new JLabel("mood");
		lblMood.setHorizontalAlignment(SwingConstants.RIGHT);
		lblMood.setText("<HTML> <b>Stato d'animo:</b> "+Mood.valueOf(user.getMood()).getText());
		GridBagConstraints gbc_lblMood = new GridBagConstraints();
		gbc_lblMood.gridwidth = 2;
		gbc_lblMood.fill = GridBagConstraints.HORIZONTAL;
		gbc_lblMood.insets = new Insets(0, 0, 5, 0);
		gbc_lblMood.gridx = 1;
		gbc_lblMood.gridy = 0;
		contentPane.add(lblMood, gbc_lblMood);

		btnChangeProfileImage = new JButton(ResourceBundle.getBundle("spotGUI.personalProfileGUI.messages").getString("PersonalProfileFrame.btnChangeProfileImage.text")); //$NON-NLS-1$ //$NON-NLS-2$
		btnChangeProfileImage.setVisible(false);
		btnChangeProfileImage.addActionListener(changeImageListener);

		comboBoxMood = new JComboBox();
		comboBoxMood.setBackground(UIManager.getColor("Desktop.background"));
		comboBoxMood.setRenderer(new ComboBoxMoodRenderer ());
		comboBoxMood.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent arg0) {
				if (arg0.getStateChange() == ItemEvent.SELECTED) {
					Mood mood;
					mood = (Mood) arg0.getItem();
					imageMood.setIcon(new ImageIcon(mood.getAssociatedIcon()));
				}
			}
		});

		comboBoxMood.setVisible(false);

		imageMood = new JLabel("");
		imageMood.setToolTipText(ResourceBundle.getBundle("spotGUI.personalProfileGUI.messages").getString("PersonalProfileFrame.imageMood.toolTipText")); //$NON-NLS-1$ //$NON-NLS-2$
		imageMood.setIcon(new ImageIcon(Mood.valueOf(user.getMood()).getAssociatedIcon()));
		GridBagConstraints gbc_imageMood = new GridBagConstraints();
		gbc_imageMood.insets = new Insets(0, 0, 5, 0);
		gbc_imageMood.anchor = GridBagConstraints.NORTHEAST;
		gbc_imageMood.gridx = 2;
		gbc_imageMood.gridy = 1;
		contentPane.add(imageMood, gbc_imageMood);
		comboBoxMood.setModel(new DefaultComboBoxModel(Mood.values()));
		GridBagConstraints gbc_comboBox = new GridBagConstraints();
		gbc_comboBox.insets = new Insets(0, 0, 5, 0);
		gbc_comboBox.fill = GridBagConstraints.HORIZONTAL;
		gbc_comboBox.gridx = 2;
		gbc_comboBox.gridy = 2;
		contentPane.add(comboBoxMood, gbc_comboBox);

		personalMessage = new JTextPane();
		personalMessage.setToolTipText(ResourceBundle.getBundle("spotGUI.personalProfileGUI.messages").getString("PersonalProfileFrame.personalMessage.toolTipText")); //$NON-NLS-1$ //$NON-NLS-2$
		personalMessage.setEditable(false);
		SimpleAttributeSet attribs = new SimpleAttributeSet();  
		StyleConstants.setAlignment(attribs , StyleConstants.ALIGN_RIGHT);  
		StyleConstants.setFontFamily(attribs, "Dialog");
		StyleConstants.setFontSize(attribs, 13);
		StyleConstants.setItalic(attribs, true);
		personalMessage.setParagraphAttributes(attribs,true);  
		GridBagConstraints gbc_personalMessage = new GridBagConstraints();
		gbc_personalMessage.gridheight = 3;
		gbc_personalMessage.gridwidth = 2;
		gbc_personalMessage.fill = GridBagConstraints.BOTH;
		gbc_personalMessage.insets = new Insets(0, 0, 5, 0);
		gbc_personalMessage.gridx = 1;
		gbc_personalMessage.gridy = 3;
		contentPane.add(personalMessage, gbc_personalMessage);
		personalMessage.setBorder(null);
		personalMessage.setOpaque(false);
		personalMessage.setText(user.getPersonalMessage());
		GridBagConstraints gbc_btnCambiaImmagineDi = new GridBagConstraints();
		gbc_btnCambiaImmagineDi.anchor = GridBagConstraints.WEST;
		gbc_btnCambiaImmagineDi.insets = new Insets(0, 0, 5, 5);
		gbc_btnCambiaImmagineDi.gridx = 0;
		gbc_btnCambiaImmagineDi.gridy = 4;
		contentPane.add(btnChangeProfileImage, gbc_btnCambiaImmagineDi);

		horizontalBox = Box.createHorizontalBox();
		GridBagConstraints gbc_horizontalBox = new GridBagConstraints();
		gbc_horizontalBox.anchor = GridBagConstraints.WEST;
		gbc_horizontalBox.insets = new Insets(0, 0, 5, 5);
		gbc_horizontalBox.gridx = 0;
		gbc_horizontalBox.gridy = 5;
		contentPane.add(horizontalBox, gbc_horizontalBox);

		btnModifyProfile = new JButton(ResourceBundle.getBundle("spotGUI.personalProfileGUI.messages").getString("PersonalProfileFrame.btnModifyProfile.text")); //$NON-NLS-1$ //$NON-NLS-2$
		horizontalBox.add(btnModifyProfile);
		btnModifyProfile.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				profile.edit();
				btnUpdateProfile.setVisible(true);
			}
		});
		btnModifyProfile.setAlignmentX(1.0f);
		if (SocialNetworkManager.getSharedInstance().getUserId() != profile.getUserId())
			btnModifyProfile.setVisible(false);

		btnUpdateProfile = new JButton(ResourceBundle.getBundle("spotGUI.personalProfileGUI.messages").getString("PersonalProfileFrame.btnUpdateProfile.text")); //$NON-NLS-1$ //$NON-NLS-2$
		btnUpdateProfile.setVisible(false);
		horizontalBox.add(btnUpdateProfile);

		progressBar = new JProgressBar();
		progressBar.setPreferredSize(new Dimension(200, 25));
		progressBar.setMinimumSize(new Dimension(200, 25));
		progressBar.setVisible(false);
		progressBar.setString(ResourceBundle.getBundle("spotGUI.personalProfileGUI.messages").getString("PersonalProfileFrame.progressBar.string")); //$NON-NLS-1$ //$NON-NLS-2$
		progressBar.setStringPainted(true);
		progressBar.setIndeterminate(true);
		horizontalBox.add(progressBar);

		btnUpdateProfile.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				btnUpdateProfile.setVisible(false);
				btnModifyProfile.setVisible(false);
				progressBar.setVisible(true);
				setEnabled(false);

				profile.update();
				progressBar.setVisible(false);
			}
		});

		splitPane = new JSplitPane();
		splitPane.setResizeWeight(0.3);
		GridBagConstraints gbc_splitPane = new GridBagConstraints();
		gbc_splitPane.insets = new Insets(0, 0, 0, 5);
		gbc_splitPane.gridwidth = 3;
		gbc_splitPane.fill = GridBagConstraints.BOTH;
		gbc_splitPane.gridx = 0;
		gbc_splitPane.gridy = 6;
		contentPane.add(splitPane, gbc_splitPane);

		scrollPanePersonalData = new JScrollPane();
		splitPane.setLeftComponent(scrollPanePersonalData);
		scrollPanePersonalData.setMaximumSize(new Dimension(100, 32767));
		scrollPanePersonalData.setOpaque(false);
		scrollPanePersonalData.setViewportView(profile.getPersonalDataManager().getView());
		scrollPanePersonalData.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

		personalElementsPanel = new ElementPanel(profile.getUserId());
		personalElementsPanel.update();
		GridBagLayout gridBagLayout = (GridBagLayout) personalElementsPanel.getLayout();
		gridBagLayout.rowHeights = new int[]{57, 0, 0};





		tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		splitPane.setRightComponent(tabbedPane);
		tabbedPane.setBorder(null);
		tabbedPane.setAlignmentX(Component.LEFT_ALIGNMENT);

		tabbedPane.add(personalElementsPanel);
		tabbedPane.setTitleAt(0, "Elementi Personali");
		tabbedPane.add(profile.getPhotoManager().getView());
		tabbedPane.setTitleAt(1, "Fotografie");
		tabbedPane.add(profile.getFamilyManager().getView());
		tabbedPane.setTitleAt(2, "Famiglia e amici");
		tabbedPane.setSelectedIndex(0);


		if (user.getSecondName() == null) {
			lblUserName.setText(user.getFirstName()+" "+user.getSurname());
		} else {
			lblUserName.setText(user.getFirstName()+" "+user.getSecondName()+" "+user.getSurname());
		}
		if (user.getNickName() != null)
			lblNickName.setText(user.getNickName());


		setExtendedState(JFrame.MAXIMIZED_BOTH);
		setVisible(true);
	}

	public void makeEditable () {
		lblNickName.setEditable(true);
		comboBoxMood.setSelectedItem(Mood.valueOf(manager.getUser(profile.getUserId()).getMood()));
		comboBoxMood.setVisible(true);
		lblMood.setText(ResourceBundle.getBundle("spotGUI.personalProfileGUI.messages").getString("PersonalProfileFrame.mood"));
		btnChangeProfileImage.setVisible(true);
	}

	public SocialUserData createNewSocialUserData () {
		SocialUserData data = new SocialUserData(profile.getUserId(), null, null, null, lblNickName.getText().equals(
				ResourceBundle.getBundle("spotGUI.personalProfileGUI.messages").getString("PersonalProfileFrame.lblNickName.text"))? null : lblNickName.getText(), -1,
				((Mood)comboBoxMood.getSelectedItem()).toString(), personalMessage.getText());
		data.setPhoto(newUserPhoto);
		return data;
	}


	private class ComboBoxMoodRenderer implements ListCellRenderer {

		private DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();

		@Override
		public Component getListCellRendererComponent(JList list, Object value,
				int index, boolean isSelected, boolean cellHasFocus) {

			JLabel listCellRendererComponent = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
			listCellRendererComponent.setText(((Mood)value).getText());
			return listCellRendererComponent;

		}
	}
}
